from flask import Flask, render_template
from flask_socketio import SocketIO
from flask_socketio import Namespace
import eventlet

# app = Flask(__name__, template_folder="templates")

# app.config['SECRET_KEY'] = 'secret!'
# socketio = SocketIO(app, engineio_logger=True, logger=True, cors_allowed_origins='http://localhost:3000')


# Create a URL route in our application for "/"
# @app.route('/')
# def home():
#     """
#     This function loads the homepage
#     """
#     return render_template('index.html')


# class-based Namespaces self.emit()代替了 修饰器namespaces 的sio.emit()
class MyCustomNamespace(Namespace):
    # 不能写
    # def __init__(self, socketio, namespace=None):
    #     super().__init__(namespace=namespace)
    #     self.socketio = socketio

    def on_connect(self):
        print("Client just connected")
        # 测试通过方法1：
        self.socketio.emit('custom_messages', {'data': 'juran send PythonClient'}, namespace='/channel_A')
        # 测试通过方法2：
        # self.emit('custom_messages', {'data': 'juran send PythonClient'})
        # 测试失败：MyCustomNamespaceM没有call属性
        # self.call('custom_messages', {'data': 'juran send PythonClient'})
        return

    def on_disconnect(self):
        print("Client just left")

    def on_messages(self, data):
        # 事件
        # self.emit('message_received', 'i come from flaskServer')
        print('***')
        print(f"\nReceived data from client: \n {data}\n")
        # 调用函数通过
        self.on_connect()
        # 调用函数通过
        self.on_myEmail('juran')
        return data

    def on_myEmail(self, name):
        self.emit('myEmail', {'hello': name})
        pass

    def on_response(self, data):
        print('********')
        print(f"\nReceived data from client: \n {data}\n")
        pass

    def on_myWechat(self, data):
        print('************')
        print(str(data))
        pass


# 注意:Flask-Socketio用on_namespace;Python-Socketio用register_namespace
# socketio.on_namespace(MyCustomNamespace('/channel_A'))

# 启动方式1：
# if __name__ == "__main__":
#     eventlet.wsgi.server(
#         eventlet.wrap_ssl(eventlet.listen(("localhost", 3000)),
#                           certfile='server.crt',
#                           keyfile='server.key',
#                           server_side=True), app)
# socketio.run(app, host="localhost", port=3000, debug=True)

# 启动方式2：
# if __name__ == '__main__':
#     SERVER_ADDRESS = ('127.0.0.1', 8000)
#     sock = eventlet.listen(SERVER_ADDRESS)
#     eventlet.wsgi.server(sock, app)
